/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.user;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import model.Campaign;
import model.Client;
import model.Resource;
import model.user.Director;
import model.user.Staff;
import util.Utilization;
import view.user.ACIListModel;
import view.user.CreateClientDialog;
import view.user.DirectorView;
import view.user.MainFrame;
import view.user.UpdateClientDialog;

/**
 *
 * @author CUNEYT
 */
public class DirectorController {

    private class UpdateClientListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            Campaign c = (Campaign) dView.getCampaignList().getSelectedValue();
            UpdateClientDialog ucd = new UpdateClientDialog(mainView, true, c.getClient(), c, director.getStaff());
            ucd.setVisible(true);

        }
    }

    private class StaffToAssignListener implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            Staff s = (Staff) dView.getStaffToAssignList().getSelectedValue();
            if (s != null) {
                dView.getAddStaffButton().setEnabled(true);
            } else {
                dView.getAddStaffButton().setEnabled(false);
            }
        }
    }

    private class AddStaffListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            Campaign c = (Campaign) dView.getCampaignList().getSelectedValue();
            Staff s = (Staff) dView.getStaffToAssignList().getSelectedValue();
            ArrayList<Staff> cs = c.getStaff();
            if (cs.contains(s)) {
                JOptionPane.showMessageDialog(dView, "Staff already assigned!");
            } else {
                c.assignStaff(s);
                dView.getStaffList().setModel(new ACIListModel(c.getStaff()));
            }

        }
    }

    private class RemoveStaffListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            Staff s = (Staff) dView.getStaffList().getSelectedValue();
            Campaign c = (Campaign) dView.getCampaignList().getSelectedValue();
            ArrayList<Staff> cs = c.getStaff();
            cs.remove(s);
            c.removeStaff(s);
            dView.getStaffList().setModel(new ACIListModel(cs));
        }
    }

    private class RemoveCampaignResourceListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            removeResource((Resource) dView.getCampaignResourceList().getSelectedValue());
        }
    }

    private class CampaignResourceSelectionChanged implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            if (dView.getCampaignResourceList().getSelectedValue() != null) {
                dView.getRemoveCampaignResourceButton().setEnabled(true);
            } else {
                dView.getRemoveCampaignResourceButton().setEnabled(false);
            }
        }
    }

    private class AddResourceListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            Resource r = (Resource) dView.getResourceList().getSelectedValue();
            double amount = 0.0;
            boolean contains = false;

            try {
                amount = Double.parseDouble(dView.getResourceAmountTextField().getText());
                if (amount > r.getAmount()) {
                    throw new NumberFormatException("Maximum amount exceeded!");
                }
                for (Iterator<Resource> it = camRes.iterator(); it.hasNext();) {
                    Resource resource = it.next();
                    if (resource.getType().equals(r.getType())) {
                        contains = true;
                        resource.add(amount);
                        break;
                    }
                }
                if (!contains) {
                    camRes.add(new Resource(r.getType(), amount));
                }

                r.add(-1 * amount);
                dView.getResourceAmountTextField().setText(String.valueOf(r.getAmount()));
                dView.getCampaignResourceList().setModel(new ACIListModel(camRes));
                dView.getResourceList().setModel(new ACIListModel(director.getResources()));
            } catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(dView, nfe);
            }
        }
    }

    private class ResourceSelectionChanged implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            if (dView.getResourceList().getSelectedValue() != null) {
                Resource r = (Resource) dView.getResourceList().getSelectedValue();
                dView.getResourceAddButton().setEnabled(true);
                dView.getResourceAmountTextField().setText(String.valueOf(r.getAmount()));
            } else {
                dView.getResourceAddButton().setEnabled(false);
                dView.getResourceAmountTextField().setText("0.0");
            }
        }
    }

    private class NegotiateButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (!dView.getcCampaignTitleTextField().getText().isEmpty()) {
                GregorianCalendar start = new GregorianCalendar(Integer.parseInt(dView.getCcStartYearComboBox().getSelectedItem().toString()),
                        dView.getCcStartMonthComboBox().getSelectedIndex(),
                        Integer.parseInt(dView.getCcStartDayComboBox().getSelectedItem().toString()));
                GregorianCalendar end = new GregorianCalendar(Integer.parseInt(dView.getCcEndYearComboBox().getSelectedItem().toString()),
                        dView.getCcEndMonthComboBox().getSelectedIndex(),
                        Integer.parseInt(dView.getCcEndDayComboBox().getSelectedItem().toString()));
                Campaign c = new Campaign(dView.getcCampaignTitleTextField().getText(), dView.getcCampaignTypeComboBox().getSelectedItem().toString(),
                        start.getTime(), end.getTime(), Campaign.NEGOTIATION, director);
                c.setClient((Client) dView.getCcClientComboBox().getSelectedItem());
                c.setResources(camRes);
                director.addCampaign(c);
                resetNegotiationFields(true);
                changeForePanel(dView.getListPanel());
            } else {
                JOptionPane.showMessageDialog(mainView, "Title of campaign cannot be empty!");
            }
        }
    }

    private class ResetButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            resetNegotiationFields(false);
        }
    }

    private class CreateClientCancelled implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            ccd.dispose();
        }
    }

    private class ClientCreateListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            ccd = new CreateClientDialog(mainView, true);
            ccd.getCreateButton().addActionListener(new CreateClientButtonListener());
            ccd.getCancelButton().addActionListener(new CreateClientCancelled());
            ccd.setVisible(true);
        }
    }

    private class CreateClientButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if ((ccd.getNameTextField().getText().isEmpty()) || (ccd.getContactInfoTextField().getText().isEmpty())) {
                JOptionPane.showMessageDialog(null, "Name and Contact Info fields cannot be empty!");
            } else {
                Utilization.addClient(ccd.getNameTextField().getText(), ccd.getGeneralInfoTextArea().getText(),
                        ccd.getContactPersonTextField().getText(), ccd.getContactInfoTextField().getText());
                ccd.dispose();
                updateClients();
            }
        }
    }

    private class StaffSelectionChanged implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            if (dView.getStaffList().getSelectedValue() != null) {
                dView.getRemoveStaffButton().setEnabled(true);
                updateStaffInfo((Staff) dView.getStaffList().getSelectedValue());
            } else {
                dView.getRemoveStaffButton().setEnabled(false);
                dView.getStaffCampaignsList().setModel(new DefaultListModel());
            }
        }
    }

    private class CampaignSelectionChanged implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            updateCampaignInfo((Campaign) dView.getCampaignList().getSelectedValue());
        }
    }

    private class CreateCampaignListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            changeForePanel(dView.getCreatePanel());

        }
    }

    private class ListCampaignsListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            changeForePanel(dView.getListPanel());
        }
    }
    private Director director;
    private DirectorView dView;
    private MainFrame mainView;
    private CreateClientDialog ccd;
    private ArrayList<Resource> camRes = null;

    public DirectorController(Director dir, DirectorView dv, MainFrame mf) {
        this.director = dir;
        this.dView = dv;
        this.director.addObserver(dv);
        this.mainView = mf;
        this.camRes = new ArrayList<Resource>();
        this.dView.addCampaignListSelectionListener(new CampaignSelectionChanged());
        this.dView.addStaffListSelectionListener(new StaffSelectionChanged());
        this.dView.addListCampaignButtonListener(new ListCampaignsListener());
        this.dView.addCreateCampaignButtonListener(new CreateCampaignListener());
        this.dView.addCreateClientButtonListener(new ClientCreateListener());
        this.dView.addResetButtonListener(new ResetButtonListener());
        this.dView.addNegotiateButtonListener(new NegotiateButtonListener());
        this.dView.getCampaignList().setModel(new ACIListModel(director.getCampaigns()));
        this.dView.getResourceList().setModel(new ACIListModel(director.getResources()));
        this.dView.getResourceList().addListSelectionListener(new ResourceSelectionChanged());
        this.dView.getCampaignResourceList().setModel(new ACIListModel(camRes));
        this.dView.getCampaignResourceList().addListSelectionListener(new CampaignResourceSelectionChanged());
        this.dView.getResourceAddButton().addActionListener(new AddResourceListener());
        this.dView.getStaffToAssignList().setModel(new ACIListModel(director.getStaff()));
        this.dView.getRemoveCampaignResourceButton().addActionListener(new RemoveCampaignResourceListener());
        this.dView.getStaffToAssignList().addListSelectionListener(new StaffToAssignListener());
        this.dView.getRemoveStaffButton().addActionListener(new RemoveStaffListener());
        this.dView.getAddStaffButton().addActionListener(new AddStaffListener());
        this.dView.getUpdateClientInfoButton().addActionListener(new UpdateClientListener());
    }

    private void removeResource(Resource r) {
        for (Iterator<Resource> it = director.getResources().iterator(); it.hasNext();) {
            Resource resource = it.next();
            if (resource.getType().equals(r.getType())) {
                resource.add(r.getAmount());
                camRes.remove(r);
                dView.getCampaignResourceList().setModel(new ACIListModel(camRes));
                dView.getResourceList().setModel(new ACIListModel(director.getResources()));
                break;
            }
        }
    }

    public ArrayList<Resource> getCamRes() {
        return camRes;
    }

    public void setCamRes(ArrayList<Resource> camRes) {
        this.camRes = camRes;
    }

    public CreateClientDialog getCcd() {
        return ccd;
    }

    public void setCcd(CreateClientDialog ccd) {
        this.ccd = ccd;
    }

    public MainFrame getMainView() {
        return mainView;
    }

    public void setMainView(MainFrame mainView) {
        this.mainView = mainView;
    }

    public DirectorView getdView() {
        return dView;
    }

    public void setdView(DirectorView dView) {
        this.dView = dView;
    }

    public Director getDirector() {
        return director;
    }

    public void setDirector(Director director) {
        this.director = director;
    }

    public void changeForePanel(javax.swing.JPanel forePanel) {
        dView.getDirectorLayeredPane().setLayer(dView.getListPanel(), 0);
        dView.getListPanel().setVisible(false);
        dView.getDirectorLayeredPane().setLayer(dView.getCreatePanel(), 1);
        dView.getCreatePanel().setVisible(false);
        dView.getDirectorLayeredPane().setLayer(forePanel, 2);
        forePanel.setVisible(true);
        camRes = new ArrayList<Resource>();
        dView.getCampaignResourceList().setModel(new ACIListModel(camRes));
    }

    private void resetNegotiationFields(boolean created) {

        GregorianCalendar now = new GregorianCalendar();

        dView.getcCampaignTitleTextField().setText("");
        dView.getCcStartDayComboBox().setSelectedItem(now.get(Calendar.DAY_OF_MONTH));
        dView.getCcStartMonthComboBox().setSelectedIndex(now.get(Calendar.MONTH));
        dView.getCcStartYearComboBox().setSelectedItem(now.get(Calendar.YEAR));
        dView.getCcEndDayComboBox().setSelectedItem(now.get(Calendar.DAY_OF_MONTH));
        dView.getCcEndMonthComboBox().setSelectedIndex(now.get(Calendar.MONTH));
        dView.getCcEndYearComboBox().setSelectedItem(now.get(Calendar.YEAR) + 1);

        if (!created) {
            for (Iterator<Resource> it = camRes.iterator(); it.hasNext();) {
                Resource resource = it.next();
                for (Iterator<Resource> it1 = director.getResources().iterator(); it1.hasNext();) {
                    Resource resource1 = it1.next();
                    if (resource.getType().equals(resource1.getType())) {
                        resource1.add(resource.getAmount());
                    }
                }
            }
        }
        camRes = new ArrayList<Resource>();
        dView.getCampaignResourceList().setModel(new ACIListModel(camRes));
        dView.getResourceList().setModel(new ACIListModel(director.getResources()));

    }

    private void updateClients() {
        dView.initiateClients();
    }

    private void updateCampaignInfo(Campaign c) {
        dView.updateCampaignFields(c);
    }

    private void updateStaffInfo(Staff s) {
        dView.updateStaffFields(s);
    }
}
